package com.andyou.rest.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.andyou.common.config.Global;
import com.andyou.common.utils.StringUtils;
import com.andyou.modules.sys.entity.User;
import com.andyou.modules.sys.service.SystemService;
import com.andyou.rest.dao.AppInfoDao;
import com.andyou.rest.entity.AppInfo;

@Service
@Transactional(readOnly = true)
public class LoginService  {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private SystemService systemService;
	
	@Autowired
	private AppInfoDao appInfoDao;
	
	@Autowired
	private AppSessionContextService appSessionContextService;
    /**
     * app 登录 
     * @param appKey
     * @param appSecret
     * @param account
     * @param password
     * @return 
     * @author lgx
     * Date:2017年4月20日；
     */
	@Transactional(readOnly = false)
	public String login(String appKey, String appSecret, String account, String password,String accessToken) {
        String message = null;
        
        if (StringUtils.isBlank(appKey) || StringUtils.isBlank(appSecret)) {
        	message = "appKey或appSecret不能为空";
        	return message;
		}
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
        	message = "account或password不能为空";
        	return message;
		}
        
        AppInfo appInfo = new AppInfo();
        appInfo.setId(appKey);//表中的id 和appKey 要一致
        appInfo = appInfoDao.get(appInfo);
        
        if (appInfo == null) {
        	message = "appKey无效";
        	return message;
		}
		
        if (!appInfo.getAppSecret().equals(appSecret)) {
        	message = "appSecret无效";
        	return message;
		}
        
        if (StringUtils.isBlank(accessToken)) {
        	message = "accessToken不能为空";
        	return message;
		}
        
        User user = systemService.getUserByLoginName(account);
		if (user != null) {
			if (Global.NO.equals(user.getLoginFlag())) {
	        	message = "该已帐号禁止登录";
	        	return message;
			}
			if (SystemService.validatePassword(password, user.getPassword())) {
				appSessionContextService.insertByappInfoAnduser(appInfo, user, accessToken);
				return message;
			}else{
	        	message = "该已帐号禁止登录";
	        	return message;
			}
		}else{
        	message = "登录用户或者密码错误";
        	return message;
		}	

	}

}
